const Constant = require('../constant/constant')
const Common = require('./common')
const UserModel = require('../models/user')
const ProviderModel = require('../models/provider')
const BillModel = require('../models/bill')
//const AddressModel = require('../models/address')
const RoleModel = require('../models/role')
const dateFormat = require('dateformat')
const md5 = require('md5')
const { Op } = require('sequelize')
const JWT = require('../utils/jwt')
const { checkToken } = require('../utils/checkToken')
const { getParams } = require('../utils/getParams')

//导出当前控制器中的数据
const exportsObject = {
  //user
  login,
  getUserList,
  deleteUserById,
  updateUserById,
  getUserById,
  createUser,
  getUserByUserCode,
  getUserByUserName,
  getUserByPhone,
  //password
  updatePassword,
  //product
  getProviderList,
  getProviderByPage,
  getProviderByProCode,
  getProviderById,
  upateProviderById,
  addProvider,
  deleteProviderById,
  //bill
  getBillList,
  updateBillById,
  getBillById,
  createBill,
  deleteBillById,
  getBillByBillCode,
}
module.exports = exportsObject

/**
 * 1、用户登录接口函数
 * @date 2021-03-17
 * @param {any} req
 * @param {any} res
 * @returns {any}
 */
function login(req, res) {
  let params = getParams(req)
  if (!params) {
    return res.send(Constant.LACK)
  }
  let resObj = Common.clone(Constant.DEFAULT_SUCCESS)
  let tasks = {
    checkParams(cb) {
      Common.checkParams(params, ['username', 'userPassword'], cb)
    },
    query: [
      'checkParams',
      (results, cb) => {
        UserModel.findOne({
          where: {
            username: params.username,
            userPassword: md5(params.userPassword),
          },
          //如果要显示关联的表smbms_role数据，添加include
          include: RoleModel,
        })
          .then((v) => {
            //console.log(v)
            if (v) {
              //保存token，过期时间60s*30
              resObj.token = new JWT().generate(v.id, 86400)
              resObj.msg = '登录成功'
              resObj.data = {
                id: v.id,
                userCode: v.userCode,
                userName: v.userName,
                userPassword: v.userPassword,
                gender: v.gender === 1 ? '男' : '女',
                phone: v.phone,
                address: v.address,
                userRole: v.userRole,
                picpath: v.picpath,
                resume: v.resume,
                createdBy: v.createdBy,
                modifyBy: v.modifyBy,
                birthday: dateFormat(v.birthday, 'yyyy-mm-dd HH:MM:ss'),
                createdAt: dateFormat(v.createdAt, 'yyyy-mm-dd HH:MM:ss'),
                updatedAt: dateFormat(v.updatedAt, 'yyyy-mm-dd HH:MM:ss'),
                roleName: v.Role.roleName,
              }
            } else {
              resObj.msg = '请输入正确的用户名或密码'
              resObj.data = null
              resObj.code = 400
            }
            //放行
            cb(null)
          })
          .catch((err) => {
            console.log(err)
            //返回错误信息到async方法中
            cb(Constant.DEFAULT_ERROR)
          })
      },
    ],
  }
  Common.autoFn(tasks, res, resObj)
}

/**
 * 2、根据用户名模糊分页查询用户列表
 * @date 2021-03-17
 * @param {any} req
 * @param {any} res
 */
function getUserList(req, res) {
  /*<------------获得用户传递的token值，进行验证--------------*/
  if (!checkToken(req, res)) {
    return
  }
  /*------------获得用户传递的token值，进行验证-------------->*/
  let params = getParams(req)
  if (!params) {
    return res.send(Constant.LACK)
  }
  let resObj = Common.clone(Constant.DEFAULT_SUCCESS)
  let tasks = {
    checkParams(cb) {
      Common.checkParams(params, ['page', 'pageSize'], cb)
    },
    query: [
      'checkParams',
      (results, cb) => {
        let offset = (params.page - 1) * params.pageSize || 0
        let limit = parseInt(params.pageSize) || 10
        let criteria = {}
        //如果userName参数传递了，就按照当前的用户名模糊分页查询
        if (params.userName) {
          criteria['userName'] = { [Op.substring]: params.userName }
        }
        UserModel.findAndCountAll({
          //where username like '%hat%'
          where: criteria,
          //分页查询的起始位置
          offset,
          //查询条数
          limit,
          //排序
          order: [['createdAt', 'desc']],
          //关联查询
          include: RoleModel,
        })
          .then(function (result) {
            let list = []
            if (result) {
              console.log(result)
              result.rows.forEach((v) => {
                let obj = {
                  id: v.id,
                  userCode: v.userCode,
                  userName: v.userName,
                  userPassword: v.userPassword,
                  gender: v.gender === 1 ? '男' : '女',
                  phone: v.phone,
                  address: v.address,
                  userRole: v.userRole,
                  picpath: v.picpath,
                  resume: v.resume,
                  createdBy: v.createdBy,
                  modifyBy: v.modifyBy,
                  birthday: dateFormat(v.birthday, 'yyyy-mm-dd HH:MM:ss'),
                  createdAt: dateFormat(v.createdAt, 'yyyy-mm-dd HH:MM:ss'),
                  updatedAt: dateFormat(v.updatedAt, 'yyyy-mm-dd HH:MM:ss'),
                  roleName: v.Role.roleName,
                }
                list.push(obj)
              })
              resObj.code = 200
              resObj.data = { list, count: result.count }
              resObj.msg = '请求用户列表数据成功'
            } else {
              resObj.code = 200
              resObj.data = null
              resObj.msg = '没有你要查找的用户列表数据'
            }
            resObj.page = +params.page
            resObj.pageSize = +params.pageSize
            //放行，不调用就不放行
            cb(null)
          })
          .catch(function (err) {
            console.log(err)
            //放行，不调用就不放行
            cb(Constant.DEFAULT_ERROR)
          })
      },
    ],
  }
  Common.autoFn(tasks, res, resObj)
}

/**
 * 3、根据用户id删除用户
 * @date 2021-03-17
 * @param {any} req
 * @param {any} res
 */
function deleteUserById(req, res) {
  let flag = checkToken(req, res)
  if (!flag) {
    return
  }
  let params = getParams(req)
  if (!params) {
    return res.send(Constant.LACK)
  }
  //1、获得一个返回值对象
  let resObj = Common.clone(Constant.DEFAULT_SUCCESS)
  //2、创建一个任务
  let tasks = {
    checkParams(cb) {
      Common.checkParams(params, ['id'], cb)
    },
    query: [
      'checkParams',
      (results, cb) => {
        UserModel.destroy({
          where: {
            id: params.id,
          },
        })
          .then((result) => {
            console.log(result)
            resObj.data = result
            resObj.msg = '删除成功'
            cb(null)
          })
          .catch((e) => {
            console.error(e)
            cb(Constant.DEFAULT_ERROR)
          })
      },
    ],
  }
  //3、统一的回复信息
  Common.autoFn(tasks, res, resObj)
}

/**
 * 4、根据用户id修改用户
 * @date 2021-03-17
 * @param {any} req
 * @param {any} res
 */
function updateUserById(req, res) {
  let flag = checkToken(req, res)
  if (!flag) {
    return
  }
  let params = getParams(req)
  if (!params) {
    return res.send(Constant.LACK)
  }
  let resObj = Common.clone(Constant.DEFAULT_SUCCESS)
  let tasks = {
    checkParams(cb) {
      Common.checkParams(
        params,
        [
          'userName',
          'gender',
          'birthday',
          'phone',
          'address',
          'userRole',
          'id',
        ],
        cb
      )
    },
    query: [
      'checkParams',
      (results, cb) => {
        UserModel.update(
          {
            userName: params.userName,
            gender: params.gender,
            birthday: params.birthday,
            phone: params.phone,
            address: params.address,
            userRole: params.userRole,
          },
          {
            where: {
              id: params.id,
            },
          }
        )
          .then((result) => {
            resObj.msg = '修改成功'
            resObj.data = result
            cb(null)
          })
          .catch((error) => {
            console.error(error)
            cb(Constant.DEFAULT_ERROR)
          })
      },
    ],
  }
  Common.autoFn(tasks, res, resObj)
}

/**
 * 5、根据id查询用户信息
 * @date 2021-03-21
 * @param {any} req
 * @param {any} res
 */
function getUserById(req, res) {
  //1、验证token
  let flag = checkToken(req, res)
  if (!flag) {
    return
  }
  //2、获得返回对象
  let resObj = Common.clone(Constant.DEFAULT_SUCCESS)
  //3、获得请求参数
  let params = getParams(req)
  if (!params) {
    return res.send(Constant.LACK)
  }
  //4、创建任务对象
  let tasks = {
    checkParams(cb) {
      Common.checkParams(params, ['id'], cb)
    },
    query: [
      'checkParams',
      (results, cb) => {
        UserModel.findOne({
          where: {
            id: params.id,
          },
          //如果要显示关联的表smbms_role数据，添加include
          include: RoleModel,
        })
          .then((v) => {
            if (v) {
              let obj = {
                id: v.id,
                userCode: v.userCode,
                userName: v.userName,
                userPassword: v.userPassword,
                gender: v.gender === 1 ? '男' : '女',
                phone: v.phone,
                address: v.address,
                userRole: v.userRole,
                picpath: v.picpath,
                resume: v.resume,
                createdBy: v.createdBy,
                modifyBy: v.modifyBy,
                birthday: dateFormat(v.birthday, 'yyyy-mm-dd HH:MM:ss'),
                createdAt: dateFormat(v.createdAt, 'yyyy-mm-dd HH:MM:ss'),
                updatedAt: dateFormat(v.updatedAt, 'yyyy-mm-dd HH:MM:ss'),
                roleName: v.Role.roleName,
              }
              resObj.user = obj
              resObj.msg = '请求成功'
            } else {
              resObj.user = null
              resObj.msg = '没有你要查找的用户'
              resObj.code = 400
            }
            cb(null)
          })
          .catch((e) => {
            console.error(e)
            cb(Constant.DEFAULT_ERROR)
          })
      },
    ],
  }
  //5、返回数据
  Common.autoFn(tasks, res, resObj)
}

/**
 * 6、添加用户信息
 * @date 2021-03-21
 * @param {any} req
 * @param {any} res
 */
function createUser(req, res) {
  //1、检查token
  let flag = checkToken(req, res)
  if (!flag) {
    return
  }
  //2、获得参数
  let params = getParams(req)
  if (!params) {
    return res.send(Constant.LACK)
  }
  //3、创建返回对象
  let resObj = Common.clone(Constant.DEFAULT_SUCCESS)
  //4、创建任务
  let tasks = {
    checkParams(cb) {
      Common.checkParams(
        params,
        [
          'userCode',
          'userName',
          'userPassword',
          'gender',
          'birthday',
          'phone',
          'address',
          'userRole',
        ],
        cb
      )
    },
    query: [
      'checkParams',
      (results, cb) => {
        UserModel.create({
          userCode: params.userCode,
          userName: params.userName,
          userPassword: md5(params.userPassword),
          gender: params.gender,
          birthday: dateFormat(params.birthday, 'yyyy-mm-dd HH:MM:ss'),
          phone: params.phone,
          address: params.address,
          userRole: params.userRole,
          createdAt: dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss'),
          updatedAt: dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss'),
        })
          .then((v) => {
            console.log(v)
            resObj.msg = '添加成功'
            resObj.data = v
            cb(null)
          })
          .catch((e) => {
            console.error(e)
            cb(Constant.DEFAULT_ERROR)
          })
      },
    ],
  }
  //5、返回数据
  Common.autoFn(tasks, res, resObj)
}

/**
 * 7、根据id修改用户的密码
 * @date 2021-03-21
 * @param {any} req
 * @param {any} res
 */
function updatePassword(req, res) {
  //1、验证token
  let flag = checkToken(req, res)
  if (!flag) {
    return
  }
  //2、获得参数
  let params = getParams(req)
  if (!params) {
    return res.send(Constant.LACK)
  }
  //3、创建返回对象
  let resObj = Common.clone(Constant.DEFAULT_SUCCESS)
  //4、创建任务
  let tasks = {
    // 4.1 验证参数
    checkParams(cb) {
      Common.checkParams(params, ['userPassword', 'id'], cb)
    },
    // 4.2 执行数据库操作
    query: [
      // 4.2.1 验证参数
      'checkParams',
      // 4.2.2 执行数据库操作
      (results, cb) => {
        UserModel.update(
          {
            //别忘了要加密后添加到数据库
            userPassword: md5(params.userPassword),
            updatedAt: dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss'),
          },
          {
            where: {
              id: params.id,
            },
          }
        )
          .then(function (result) {
            if (!result || result.length === 0) {
              resObj.data = null
              resObj.msg = '修改失败'
              resObj.code = 400
            } else {
              resObj.data = result
              resObj.msg = '修改成功'
              resObj.code = 200
            }
            cb(null)
          })
          .catch(function (e) {
            console.error(e)
            cb(Constant.DEFAULT_ERROR)
          })
      },
    ],
  }
  //5、返回数据
  Common.autoFn(tasks, res, resObj)
}

/**
 * 8、请求供应商列表
 * @param {*} req
 * @param {*} res
 */
function getProviderList(req, res) {
  //1、检查token
  let flag = checkToken(req, res)
  if (!flag) {
    return
  }
  //2、获得返回对象
  let resObj = Common.clone(Constant.DEFAULT_SUCCESS)
  //3、创建任务对象
  let tasks = {
    query(cb) {
      ProviderModel.findAll()
        .then((result) => {
          let list = []
          result.forEach((v) => {
            let obj = {
              id: v.id,
              proCode: v.proCode,
              proName: v.proName,
              proDesc: v.proDesc,
              proContact: v.proContact,
              proPhone: v.proPhone,
              proAddress: v.proAddress,
              proFax: v.proFax,
              createdBy: v.createdBy,
              createdAt: dateFormat(v.createdAt, 'yyyy-mm-dd HH:MM:ss'),
              modifyBy: v.modifyBy,
              updatedAt: dateFormat(v.updatedAt, 'yyyy-mm-dd HH:MM:ss'),
            }
            list.push(obj)
          })
          resObj.code = 200
          resObj.msg = '请求列表成功'
          resObj.data = { list }
          cb(null)
        })
        .catch((err) => {
          console.error(err)
          cb(Constant.DEFAULT_ERROR)
        })
    },
  }
  //4、返回数据
  Common.autoFn(tasks, res, resObj)
}

/**
 * 9、请求账单列表
 * @param {*} req
 * @param {*} res
 */
function getBillList(req, res) {
  //1、检查token
  let flag = checkToken(req, res)
  if (!flag) {
    return
  }
  //2、检查参数
  let params = getParams(req)
  if (!params) {
    return res.send(Constant.LACK)
  }
  //3、创建返回对象
  let resObj = Common.clone(Constant.DEFAULT_SUCCESS)
  //4、创建任务对象
  let tasks = {
    checkParams(cb) {
      Common.checkParams(params, ['page', 'pageSize'], cb)
    },
    query: [
      'checkParams',
      (results, cb) => {
        let offset = (params.page - 1) * params.pageSize || 0
        let limit = parseInt(params.pageSize) || 10
        let criteria = {}
        //如果userName参数传递了，就按照当前的用户名模糊分页查询
        if (params.productName) {
          criteria['productName'] = { [Op.substring]: params.productName }
        } else if (params.providerId) {
          criteria['providerId'] = { [Op.eq]: params.providerId }
        } else if (params.isPayment) {
          criteria['isPayment'] = { [Op.eq]: params.isPayment }
        }
        BillModel.findAndCountAll({
          where: criteria,
          offset,
          limit,
          //排序
          order: [['createdAt', 'desc']],
          //关联查询
          include: ProviderModel,
        })
          .then((result) => {
            let list = []
            result.rows.forEach((v) => {
              let obj = {
                id: v.id,
                billCode: v.billCode,
                productName: v.productName,
                productDesc: v.productDesc,
                productUnit: v.productUnit,
                productCount: v.productCount,
                totalPrice: v.totalPrice,
                isPayment: v.isPayment,
                createdBy: v.createdBy,
                createdAt: dateFormat(v.createdAt, 'yyyy-mm-dd HH:MM:ss'),
                modifyBy: v.modifyBy,
                updatedAt: dateFormat(v.updatedAt, 'yyyy-mm-dd HH:MM:ss'),
                providerId: v.providerId,
                proName: v.Provider.proName,
              }
              list.push(obj)
            })
            resObj.data = { list, count: result.count }
            if (result.rows.length > 0) {
              resObj.msg = '请求账单列表数据成功'
            } else {
              resObj.code = 400
              resObj.msg = '指定的账单不存在'
            }
            resObj.page = +params.page
            resObj.pageSize = +params.pageSize
            resObj.providerId = +params.providerId || 0
            resObj.productName = params.productName || ''
            resObj.isPayment = +params.isPayment || ''
            cb(null)
          })
          .catch((err) => {
            console.error(err)
            cb(Constant.DEFAULT_ERROR)
          })
      },
    ],
  }
  //5、返回数据
  Common.autoFn(tasks, res, resObj)
}

/**
 * 10、根据id修改账单
 * @date 2021-03-23
 * @param {any} req
 * @param {any} res
 */
function updateBillById(req, res) {
  //1、检查token
  if (!checkToken(req, res)) {
    return
  }
  //2、检查参数
  let params = getParams(req)
  if (!params) {
    return res.send(Constant.LACK)
  }
  //3、获得返回值对象
  let resObj = Common.clone(Constant.DEFAULT_SUCCESS)
  //4、创建任务
  let tasks = {
    //4.1 检查参数
    checkParams(cb) {
      Common.checkParams(
        params,
        [
          'id',
          'billCode',
          'productName',
          'productUnit',
          'productCount',
          'totalPrice',
          'providerId',
          'isPayment',
        ],
        cb
      )
    },
    query: [
      'checkParams',
      (results, cb) => {
        //执行修改操作
        BillModel.update(
          {
            billCode: params.billCode,
            productName: params.productName,
            productUnit: params.productUnit,
            productCount: params.productCount,
            totalPrice: params.totalPrice,
            providerId: params.providerId,
            isPayment: params.isPayment,
            updatedAt: dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss'),
          },
          { where: { id: params.id } }
        )
          .then((v) => {
            if (!v || v.length === 0) {
              resObj.msg = '修改失败'
              resObj.code = 400
              resObj.data = null
            } else {
              resObj.msg = '修改成功'
              resObj.code = 200
              resObj.data = v
            }
            cb(null)
          })
          .catch((e) => {
            console.error(e)
            cb(Constant.DEFAULT_ERROR)
          })
      },
    ],
  }
  //5、返回数据
  Common.autoFn(tasks, res, resObj)
}

/**
 * 11、根据id获得一条账单信息
 * @date 2021-03-23
 * @param {any} req
 * @param {any} res
 */
function getBillById(req, res) {
  //1、检查token
  if (!checkToken(req, res)) {
    return
  }
  //2、检查参数
  let params = getParams(req)
  if (!params) {
    return res.send(Constant.LACK)
  }
  //3、获得返回值对象
  let resObj = Common.clone(Constant.DEFAULT_SUCCESS)
  //4、创建任务对象
  let tasks = {
    checkParams(cb) {
      Common.checkParams(params, ['id'], cb)
    },
    query: [
      'checkParams',
      (results, cb) => {
        BillModel.findOne({
          where: {
            id: params.id,
          },
          //如果要显示关联的表smbms_role数据，添加include
          include: ProviderModel,
        })
          .then((v) => {
            if (v) {
              let bill = {
                id: v.id,
                billCode: v.billCode,
                productName: v.productName,
                productDesc: v.productDesc,
                productUnit: v.productUnit,
                productCount: v.productCount,
                totalPrice: v.totalPrice,
                isPayment: v.isPayment,
                createdBy: v.createdBy,
                createdAt: dateFormat(v.createdAt, 'yyyy-mm-dd HH:MM:ss'),
                modifyBy: v.modifyBy,
                updatedAt: dateFormat(v.updatedAt, 'yyyy-mm-dd HH:MM:ss'),
                providerId: v.providerId,
                proName: v.Provider.proName,
              }
              resObj.data = bill
              resObj.msg = '查找成功'
            } else {
              resObj.data = null
              resObj.msg = '没有你要查找的账单'
              resObj.code = 404
            }
            cb(null)
          })
          .catch((e) => {
            console.error(e)
            cb(Constant.DEFAULT_ERROR)
          })
      },
    ],
  }
  //5、返回数据
  Common.autoFn(tasks, res, resObj)
}

/**
 * 12、根据用户编码获得当前用户
 * @date 2021-03-23
 * @param {any} req
 * @param {any} res
 */
function getUserByUserCode(req, res) {
  //1、检查token
  if (!checkToken(req, res)) {
    return
  }
  //2、检查参数
  let params = getParams(req)
  if (!params) {
    return res.send(Constant.LACK)
  }
  //3、获得返回值对象
  let resObj = Common.clone(Constant.DEFAULT_SUCCESS)
  let tasks = {
    checkParams(cb) {
      Common.checkParams(params, ['userCode'], cb)
    },
    query: [
      'checkParams',
      (results, cb) => {
        UserModel.findOne({
          where: {
            userCode: params.userCode,
          },
          //如果要显示关联的表smbms_role数据，添加include
          include: RoleModel,
        })
          .then((v) => {
            if (v) {
              resObj.user = {
                id: v.id,
                userCode: v.userCode,
                userName: v.userName,
                userPassword: v.userPassword,
                gender: v.gender === 1 ? '男' : '女',
                phone: v.phone,
                address: v.address,
                userRole: v.userRole,
                picpath: v.picpath,
                resume: v.resume,
                createdBy: v.createdBy,
                modifyBy: v.modifyBy,
                birthday: dateFormat(v.birthday, 'yyyy-mm-dd HH:MM:ss'),
                createdAt: dateFormat(v.createdAt, 'yyyy-mm-dd HH:MM:ss'),
                updatedAt: dateFormat(v.updatedAt, 'yyyy-mm-dd HH:MM:ss'),
                roleName: v.Role.roleName,
              }
              resObj.code = 200
              resObj.msg = '获得成功'
            } else {
              resObj.code = 404
              resObj.msg = '没有此用户编码的用户'
              resObj.user = null
            }
            cb(null)
          })
          .catch((e) => {
            console.error(e)
            cb(Constant.DEFAULT_ERROR)
          })
      },
    ],
  }
  Common.autoFn(tasks, res, resObj)
}

/**
 * 13、根据用户名获得当前用户
 * @date 2021-03-23
 * @param {any} req
 * @param {any} res
 */
function getUserByUserName(req, res) {
  //1、检查token
  if (!checkToken(req, res)) {
    return
  }
  //2、检查参数
  let params = getParams(req)
  if (!params) {
    return res.send(Constant.LACK)
  }
  //3、获得返回值对象
  let resObj = Common.clone(Constant.DEFAULT_SUCCESS)
  let tasks = {
    checkParams(cb) {
      Common.checkParams(params, ['userName'], cb)
    },
    query: [
      'checkParams',
      (results, cb) => {
        UserModel.findOne({
          where: {
            userName: params.userName,
          },
          //如果要显示关联的表smbms_role数据，添加include
          include: RoleModel,
        })
          .then((v) => {
            if (v) {
              resObj.user = {
                id: v.id,
                userCode: v.userCode,
                userName: v.userName,
                userPassword: v.userPassword,
                gender: v.gender === 1 ? '男' : '女',
                phone: v.phone,
                address: v.address,
                userRole: v.userRole,
                picpath: v.picpath,
                resume: v.resume,
                createdBy: v.createdBy,
                modifyBy: v.modifyBy,
                birthday: dateFormat(v.birthday, 'yyyy-mm-dd HH:MM:ss'),
                createdAt: dateFormat(v.createdAt, 'yyyy-mm-dd HH:MM:ss'),
                updatedAt: dateFormat(v.updatedAt, 'yyyy-mm-dd HH:MM:ss'),
                roleName: v.Role.roleName,
              }
              resObj.code = 200
              resObj.msg = '获得成功'
            } else {
              resObj.code = 404
              resObj.msg = '没有此用户名的用户'
              resObj.user = null
            }
            cb(null)
          })
          .catch((e) => {
            console.error(e)
            cb(Constant.DEFAULT_ERROR)
          })
      },
    ],
  }
  Common.autoFn(tasks, res, resObj)
}

/**
 * 14、根据电话获得当前用户
 * @date 2021-03-23
 * @param {any} req
 * @param {any} res
 */
function getUserByPhone(req, res) {
  //1、检查token
  if (!checkToken(req, res)) {
    return
  }
  //2、检查参数
  let params = getParams(req)
  if (!params) {
    return res.send(Constant.LACK)
  }
  //3、获得返回值对象
  let resObj = Common.clone(Constant.DEFAULT_SUCCESS)
  let tasks = {
    checkParams(cb) {
      Common.checkParams(params, ['phone'], cb)
    },
    query: [
      'checkParams',
      (results, cb) => {
        UserModel.findOne({
          where: {
            phone: params.phone,
          },
          //如果要显示关联的表smbms_role数据，添加include
          include: RoleModel,
        })
          .then((v) => {
            if (v) {
              resObj.user = {
                id: v.id,
                userCode: v.userCode,
                userName: v.userName,
                userPassword: v.userPassword,
                gender: v.gender === 1 ? '男' : '女',
                phone: v.phone,
                address: v.address,
                userRole: v.userRole,
                picpath: v.picpath,
                resume: v.resume,
                createdBy: v.createdBy,
                modifyBy: v.modifyBy,
                birthday: dateFormat(v.birthday, 'yyyy-mm-dd HH:MM:ss'),
                createdAt: dateFormat(v.createdAt, 'yyyy-mm-dd HH:MM:ss'),
                updatedAt: dateFormat(v.updatedAt, 'yyyy-mm-dd HH:MM:ss'),
                roleName: v.Role.roleName,
              }
              resObj.code = 200
              resObj.msg = '获得成功'
            } else {
              resObj.code = 404
              resObj.msg = '没有此用户名的用户'
              resObj.user = null
            }
            cb(null)
          })
          .catch((e) => {
            console.error(e)
            cb(Constant.DEFAULT_ERROR)
          })
      },
    ],
  }
  Common.autoFn(tasks, res, resObj)
}

/**
 * 15、添加账单
 * @date 2021-03-24
 * @param {any} req
 * @param {any} res
 */
function createBill(req, res) {
  //1、token拦截
  if (!checkToken(req, res)) {
    return
  }
  //2、参数获得
  let params = getParams(req)
  if (!params) {
    return res.send(Constant.LACK)
  }
  //3、创建返回对象
  let resObj = Common.clone(Constant.DEFAULT_SUCCESS)
  //4、创建任务对象
  let tasks = {
    checkParams(cb) {
      Common.checkParams(
        params,
        [
          'billCode',
          'productName',
          'productUnit',
          'productCount',
          'totalPrice',
          'providerId',
          'isPayment',
        ],
        cb
      )
    },
    query: [
      'checkParams',
      (results, cb) => {
        BillModel.create({
          billCode: params.billCode,
          productName: params.productName,
          productUnit: params.productUnit,
          productCount: params.productCount,
          totalPrice: params.totalPrice,
          isPayment: params.isPayment,
          providerId: params.providerId,
          productDesc: params.productDesc || '没有描述',
          createdBy: 1,
          modifyBy: 1,
          createdAt: dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss'),
          updatedAt: dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss'),
        })
          .then(function (v) {
            if (!v) {
              resObj.msg = '添加失败'
              resObj.code = 400
              resObj.data = null
            } else {
              resObj.msg = '添加成功'
              resObj.data = v
            }
            cb(null)
          })
          .catch(function (err) {
            console.error(err)
            cb(Constant.DEFAULT_ERROR)
          })
      },
    ],
  }
  //5、返回数据
  Common.autoFn(tasks, res, resObj)
}

/**
 * 16、删除账单
 * @date 2021-03-24
 * @param {any} req
 * @param {any} res
 */
function deleteBillById(req, res) {
  //1、token拦截
  if (!checkToken(req, res)) {
    return
  }
  //2、参数获得
  let params = getParams(req)
  if (!params) {
    return res.send(Constant.LACK)
  }
  //3、创建返回对象
  let resObj = Common.clone(Constant.DEFAULT_SUCCESS)
  //4、创建任务对象
  let tasks = {
    checkParams(cb) {
      Common.checkParams(params, ['id'], cb)
    },
    query: [
      'checkParams',
      (results, cb) => {
        BillModel.destroy({
          where: {
            id: params.id,
          },
        })
          .then(function (v) {
            if (v) {
              resObj.data = v
              resObj.msg = '删除成功'
            } else {
              resObj.data = v
              resObj.msg = '删除失败'
            }
            cb(null)
          })
          .catch(function (err) {
            console.error(err)
            cb(Constant.DEFAULT_ERROR)
          })
      },
    ],
  }
  //5、返回数据
  Common.autoFn(tasks, res, resObj)
}

/**
 * 17、根据订单编号查找订单
 * @date 2021-03-24
 * @param {any} req
 * @param {any} res
 */
function getBillByBillCode(req, res) {
  //1、检查token
  if (!checkToken(req, res)) {
    return
  }
  //2、检查参数
  let params = getParams(req)
  if (!params) {
    return res.send(Constant.LACK)
  }
  //3、获得返回值对象
  let resObj = Common.clone(Constant.DEFAULT_SUCCESS)
  //4、创建任务对象
  let tasks = {
    checkParams(cb) {
      Common.checkParams(params, ['billCode'], cb)
    },
    query: [
      'checkParams',
      (results, cb) => {
        BillModel.findOne({
          where: {
            billCode: params.billCode,
          },
          //如果要显示关联的表smbms_provider数据，添加include
          include: ProviderModel,
        })
          .then((v) => {
            if (v) {
              let bill = {
                id: v.id,
                billCode: v.billCode,
                productName: v.productName,
                productDesc: v.productDesc,
                productUnit: v.productUnit,
                productCount: v.productCount,
                totalPrice: v.totalPrice,
                isPayment: v.isPayment,
                createdBy: v.createdBy,
                createdAt: dateFormat(v.createdAt, 'yyyy-mm-dd HH:MM:ss'),
                modifyBy: v.modifyBy,
                updatedAt: dateFormat(v.updatedAt, 'yyyy-mm-dd HH:MM:ss'),
                providerId: v.providerId,
                proName: v.Provider.proName,
              }
              resObj.data = bill
              resObj.msg = '查找成功'
            } else {
              resObj.data = null
              resObj.msg = '没有你要查找的账单'
              resObj.code = 404
            }
            cb(null)
          })
          .catch((e) => {
            console.error(e)
            cb(Constant.DEFAULT_ERROR)
          })
      },
    ],
  }
  //5、返回数据
  Common.autoFn(tasks, res, resObj)
}

/**
 * 18、根据商品名称模糊分页查询
 * @date 2021-03-24
 * @param {any} req
 * @param {any} res
 */
function getProviderByPage(req, res) {
  if (!checkToken(req, res)) {
    return
  }
  let params = getParams(req)
  if (!params) {
    return res.send(Constant.LACK)
  }
  let resObj = Common.clone(Constant.DEFAULT_SUCCESS)
  let tasks = {
    checkParams(cb) {
      Common.checkParams(params, ['page', 'rows'], cb)
    },
    query: [
      'checkParams',
      (results, cb) => {
        let offset = (+params.page - 1) * params.rows
        let limit = +params.rows
        let criteria = {}
        if (params['proName']) {
          criteria['proName'] = params['proName']
        }
        ProviderModel.findAndCountAll({
          where: criteria,
          offset,
          limit,
          order: [['createdAt', 'desc']],
        })
          .then(function (result) {
            let list = []
            if (result) {
              result.rows.forEach((v) => {
                let obj = {
                  id: v.id,
                  proCode: v.proCode,
                  proName: v.proName,
                  proDesc: v.proDesc,
                  proContact: v.proContact,
                  proPhone: v.proPhone,
                  proAddress: v.proAddress,
                  proFax: v.proFax,
                  createdBy: v.createdBy,
                  createdAt: dateFormat(v.createdAt, 'yyyy-mm-dd HH:MM:ss'),
                  modifyBy: v.modifyBy,
                  updatedAt: dateFormat(v.updatedAt, 'yyyy-mm-dd HH:MM:ss'),
                }
                list.push(obj)
              })
              resObj.code = 200
              resObj.data = { list, count: result.count }
              resObj.msg = '查询供应商列表成功'
            } else {
              resObj.code = 404
              resObj.data = null
              resObj.msg = '查询的供应商不存在'
            }
            cb(null)
          })
          .catch(function (err) {
            console.error(err)
            cb(Constant.DEFAULT_ERROR)
          })
      },
    ],
  }
  Common.autoFn(tasks, res, resObj)
}

/**
 * 19、根据供应商编号查找供应商
 * @date 2021-03-24
 * @param {any} req
 * @param {any} res
 */
function getProviderByProCode(req, res) {
  //1、检查token
  if (!checkToken(req, res)) {
    return
  }
  //2、检查参数
  let params = getParams(req)
  if (!params) {
    return res.send(Constant.LACK)
  }
  //3、获得返回值对象
  let resObj = Common.clone(Constant.DEFAULT_SUCCESS)
  let tasks = {
    checkParams(cb) {
      Common.checkParams(params, ['proCode'], cb)
    },
    query: [
      'checkParams',
      (results, cb) => {
        UserModel.findOne({
          where: {
            proCode: params.proCode,
          },
        })
          .then((v) => {
            if (v) {
              resObj.provider = {
                id: v.id,
                proCode: v.proCode,
                proName: v.proName,
                proDesc: v.proDesc,
                proContact: v.proContact,
                proPhone: v.proPhone,
                proAddress: v.proAddress,
                proFax: v.proFax,
                createdBy: v.createdBy,
                createdAt: dateFormat(v.createdAt, 'yyyy-mm-dd HH:MM:ss'),
                modifyBy: v.modifyBy,
                updatedAt: dateFormat(v.updatedAt, 'yyyy-mm-dd HH:MM:ss'),
              }
              resObj.code = 200
              resObj.msg = '查询供应商成功'
            } else {
              resObj.code = 404
              resObj.msg = '没有此编号的供应商'
              resObj.user = null
            }
            cb(null)
          })
          .catch((e) => {
            console.error(e)
            cb(Constant.DEFAULT_ERROR)
          })
      },
    ],
  }
  Common.autoFn(tasks, res, resObj)
}

/**
 * 20、根据id获得供应商
 * @param {Object} req
 * @param {Object} res
 */
function getProviderById(req, res) {
  if (!checkToken(req, res)) {
    return
  }
  let params = getParams(req)
  if (!params) {
    return res.send(Constant.LACK)
  }
  let resObj = Common.clone(Constant.DEFAULT_SUCCESS)
  let tasks = {
    checkParams(cb) {
      Common.checkParams(params, ['id'], cb)
    },
    query: [
      'checkParams',
      (results, cb) => {
        ProviderModel.findByPk(params.id)
          .then((v) => {
            if (v) {
              resObj.provider = {
                id: v.id,
                proCode: v.proCode,
                proName: v.proName,
                proDesc: v.proDesc,
                proContact: v.proContact,
                proPhone: v.proPhone,
                proAddress: v.proAddress,
                proFax: v.proFax,
                createdBy: v.createdBy,
                modifyBy: v.modifyBy,
                createdAt: dateFormat(v.createdAt, 'yyyy-mm-dd HH:MM:ss'),
                updatedAt: dateFormat(v.updatedAt, 'yyyy-mm-dd HH:MM:ss'),
              }
              resObj.msg = '请求供应商成功'
            } else {
              resObj.provider = null
              resObj.code = 404
              resObj.msg = '请求的供应商不存在'
            }
            cb(null)
          })
          .catch((err) => {
            console.error(err)
            cb(Constant.DEFAULT_ERROR)
          })
      },
    ],
  }
  Common.autoFn(tasks, res, resObj)
}

/**
 * 21、根据id修改供应商
 * @param {*} req
 * @param {*} res
 */
function upateProviderById(req, res) {
  //1、检查token
  if (!checkToken(req, res)) {
    return
  }
  //2、检查参数
  let params = getParams(req)
  if (!params) {
    return res.send(Constant.LACK)
  }
  //3、获得返回值对象
  let resObj = Common.clone(Constant.DEFAULT_SUCCESS)
  //4、创建任务
  let tasks = {
    //4.1 检查参数
    checkParams(cb) {
      Common.checkParams(params, ['id', 'proCode', 'proName', 'proContact'], cb)
    },
    query: [
      'checkParams',
      (results, cb) => {
        let criteria = {
          updatedAt: dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss'),
        }
        //把params对象的属性和值全部赋予criteria
        for (let item in params) {
          if (params[item] && item !== 'id') {
            criteria[item] = params[item]
          }
        }
        //执行修改操作
        ProviderModel.update(criteria, { where: { id: params.id } })
          .then((v) => {
            if (!v || v.length === 0) {
              resObj.msg = '修改失败'
              resObj.code = 400
              resObj.data = null
            } else {
              resObj.msg = '修改成功'
              resObj.code = 200
              resObj.data = v
            }
            cb(null)
          })
          .catch((e) => {
            console.error(e)
            cb(Constant.DEFAULT_ERROR)
          })
      },
    ],
  }
  //5、返回数据
  Common.autoFn(tasks, res, resObj)
}

/**
 * 22、添加供应商
 * @date 2021-03-24
 * @param {any} req
 * @param {any} res
 */
function addProvider(req, res) {
  //1、检查token
  let flag = checkToken(req, res)
  if (!flag) {
    return
  }
  //2、获得参数
  let params = getParams(req)
  if (!params) {
    return res.send(Constant.LACK)
  }
  //3、创建返回对象
  let resObj = Common.clone(Constant.DEFAULT_SUCCESS)
  //4、创建任务
  let tasks = {
    checkParams(cb) {
      Common.checkParams(
        params,
        [
          'proCode',
          'proName',
          'proDesc',
          'proContact',
          'proPhone',
          'proAddress',
          'proFax',
          'createdBy',
          'modifyBy',
        ],
        cb
      )
    },
    query: [
      'checkParams',
      (results, cb) => {
        ProviderModel.create({
          proCode: params.proCode,
          proName: params.proName,
          proDesc: params.proDesc,
          proContact: params.proContact,
          proPhone: params.proPhone,
          proAddress: params.proAddress,
          proFax: params.proFax,
          createdBy: params.createdBy,
          modifyBy: params.modifyBy,
          createdAt: dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss'),
          updatedAt: dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss'),
        })
          .then((v) => {
            if (!v || v.length === 0) {
              resObj.msg = '添加失败'
              resObj.data = null
              resObj.code = 203
            } else {
              resObj.msg = '添加成功'
              resObj.data = v
            }
            cb(null)
          })
          .catch((e) => {
            console.error(e)
            cb(Constant.DEFAULT_ERROR)
          })
      },
    ],
  }
  //5、返回数据
  Common.autoFn(tasks, res, resObj)
}

/**
 * 23、根据id删除供应商
 * @date 2021-03-24
 * @param {any} req
 * @param {any} res
 */
function deleteProviderById(req, res) {
  //1、token拦截
  if (!checkToken(req, res)) {
    return
  }
  //2、参数获得
  let params = getParams(req)
  if (!params) {
    return res.send(Constant.LACK)
  }
  //3、创建返回对象
  let resObj = Common.clone(Constant.DEFAULT_SUCCESS)
  //4、创建任务对象
  let tasks = {
    checkParams(cb) {
      Common.checkParams(params, ['id'], cb)
    },
    query: [
      'checkParams',
      (results, cb) => {
        ProviderModel.destroy({
          where: {
            id: params.id,
          },
        })
          .then(function (v) {
            if (v) {
              resObj.data = v
              resObj.msg = '删除成功'
            } else {
              resObj.data = v
              resObj.msg = '删除失败'
            }
            cb(null)
          })
          .catch(function (err) {
            console.error(err)
            cb(Constant.DEFAULT_ERROR)
          })
      },
    ],
  }
  //5、返回数据
  Common.autoFn(tasks, res, resObj)
}
